package com.guangzhoujiayou.controller;

import cn.hutool.http.HttpUtil;
import com.guangzhoujiayou.bean.R;
import com.guangzhoujiayou.bean.User;
import com.guangzhoujiayou.bean.WxSession;
import com.guangzhoujiayou.config.WxConfig;
import com.guangzhoujiayou.jwt.JwtTokenUtil;
import com.guangzhoujiayou.service.UserService;
import com.guangzhoujiayou.utils.GsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private UserService userService;

    @RequestMapping("/wxLogin/{code}")
    public R wxLogin(@PathVariable("code") String code){
        if (StringUtils.isEmpty(code)){
            return R.fail().setMessage("参数错误");
        }
        WxSession wxSession = null;
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                    "appid=" + wxConfig.getAppid() +
                    "&secret=" + wxConfig.getSecret() +
                    "&js_code=" + code +
                    "&grant_type=authorization_code";
            String s = HttpUtil.get(url);
            wxSession = GsonUtil.fromJson(s, WxSession.class);
            if (null == wxSession || 0 != wxSession.getErrcode()) {
                return R.fail().setMessage("请求微信失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail().setMessage("请求微信失败");
        }
        User user = userService.findOneByUnionid(wxSession.getUnionid());
        if (null == user) {
            user = new User();
            user.setUnionid(wxSession.getUnionid());
            userService.save(user);
        }
        try {
            String token = jwtTokenUtil.generateToken(String.valueOf(user.getId()), null);
            return R.success().setData(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.fail().setMessage("操作失败");
    }

}
